#include "wenjian.h"
#include "ui_wenjian.h"
#include <QMessageBox>
#include <QDebug>
#include <QFileDialog>

wenjian::wenjian(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::wenjian)
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::connected, this, &wenjian::onConnected);
    connect(socket, &QTcpSocket::readyRead, this, &wenjian::onReadyRead);
    connect(socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &wenjian::onError);

    socket->connectToHost("192.168.159.131", 1234);
}

wenjian::~wenjian()
{
    delete ui;
}

void wenjian::onConnected() {
    qDebug() << "已连接到服务器！";
}

void wenjian::onReadyRead() {
    QByteArray data = socket->readAll();
    QDataStream stream(&data, QIODevice::ReadOnly);
    QString message;
    stream >> message;

    int spaceIndex = message.indexOf('\n'); // 寻找第一个空格的位置

    QString responseType = message.left(spaceIndex);
    QString Data = message.mid(spaceIndex + 1);

    if (responseType == "TIREN2_SUCCESS") {
        QMessageBox::information(this, "提示", "踢人成功");
        this->close();  // 关闭当前窗口
    } else if (responseType == "TIREN2_FAIL") {
        QMessageBox::warning(this, "提示", "请输入正确用户名");
    } else if (responseType == "WENJIAN_SUCCESS") {
        QMessageBox::information(this, "提示", "文件传输成功");
        this->close();  // 关闭当前窗口
    } else if (responseType == "WENJIAN_FAIL") {
        QMessageBox::warning(this, "提示", "文件传输失败");
    }
}

void wenjian::onError(QAbstractSocket::SocketError socketError) {
    qDebug() << "Socket错误:" << socketError;
}

void wenjian::on_queren_clicked()
{
    QString username = ui->yonghuming->text();
    QString filepath = ui->wenjian2->text();
    if (username.isEmpty() || filepath.isEmpty()) {
        QMessageBox::warning(this, "提示", "用户名,文件路径不能为空");
    } else {
        QFileInfo fileInfo(filepath);
        QString fileName = fileInfo.fileName();
        QString message = "WENJIAN\n" + username + "\n" + fileName + "\n";
        socket->write(message.toUtf8());
        // 向服务器发送文件
        QFile file(filepath);
        if(!file.open(QIODevice::ReadOnly)) {
            qDebug() << "打开文件失败";
            QMessageBox::warning(this, "提示", "打开文件失败");
            return;
        }

        QByteArray fileData = file.readAll();
        socket->write(fileData);
        file.close();

        qDebug() << "发送信息";
    }
}

void wenjian::on_fanhui_clicked()
{
    this->close();
}

void wenjian::on_liulan_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择文件");
    if (!fileName.isEmpty()) {
        ui->wenjian2->setText(fileName);
    }
}
